@use "sass:math";

/// Removes the unit (e.g. px, em, rem) from a value, returning the number only.
/// @param {Number} $num - Number to strip unit from.
/// @return {Number} The same number, sans unit.
/// @access private

/// Divide the given `$divident` by the given `$divisor`.
///
/// @param {Number} $divident - The divident.
/// @param {Number} $divisor - The divisor.
/// @param {Number} $precision - The precision decimals for the division.
///
/// @return {Number} The product of the division.
@function divide($dividend, $divisor, $precision: 12) {
  $sign: if($dividend > 0 and $divisor > 0 or $dividend < 0 and $divisor < 0, 1, -1);
  $dividend: math.abs($dividend);
  $divisor: math.abs($divisor);
  @if $dividend == 0 {
    @return 0;
  }
  @if $divisor == 0 {
    @error 'Cannot divide by 0';
  }
  $remainder: $dividend;
  $result: 0;
  $factor: 10;
  @while ($remainder > 0 and $precision >= 0) {
    $quotient: 0;
    @while ($remainder >= $divisor) {
      $remainder: $remainder - $divisor;
      $quotient: $quotient + 1;
    }
    $result: $result * 10 + $quotient;
    $factor: $factor * 0.1;
    $remainder: $remainder * 10;
    $precision: $precision - 1;
    @if ($precision < 0 and $remainder >= $divisor * 5) {
      $result: $result + 1;
    }
  }
  $result: $result * $factor * $sign;
  $dividend-unit: unit($dividend);
  $divisor-unit: unit($divisor);
  $unit-map: (
    'px': 1px,
    'rem': 1rem,
    'em': 1em,
    '%': 1%
  );
  @if ($dividend-unit != $divisor-unit and map-has-key($unit-map, $dividend-unit)) {
    $result: $result * map-get($unit-map, $dividend-unit);
  }

  @return $result;
}

@function strip-unit($num) {
  @return divide($num, $num * 0 + 1);
}
